package amazon;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;

import com.google.gson.Gson;


public class AmazonReviewConvertTool {
	
	public static void main(String[] args) throws IOException{
		String inputFile="/home/wenting/Documents/MongoDBDataset/movies/movies.txt";
		String outputFile = "/home/wenting/Documents/MongoDBDataset/movies/importData.json";
		
		File file = new File(inputFile);
		BufferedReader br = new BufferedReader(new FileReader(file));
		BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
		          new FileOutputStream(outputFile)));

		Review r;
		int i=0;//convert top ten items
			while((r=getReview(br))!=null && i<10){
				Gson gson = new Gson();
				writer.write(gson.toJson(r));	
				writer.newLine();
				
			}
		
		writer.flush();
		br.close();
	}

	public static Review getReview(BufferedReader br) throws IOException{
		Review review = new Review();
		String line;
		for(int i=0;i<9;i++){
			line = br.readLine();
			if(line == null){
				return null;
			}
			else{
				String[] array=line.split(": ");
				if(array.length==2){
					String index = array[0];
					String content = array[1];
					if(index.startsWith("product/productId"))
						review.setProductID(content);
					else if(index.startsWith("review/userId")){
						review.setUserId(content);
					}
					else if(index.startsWith("review/time")){
						review.setTime(content);
						review.setHour(String.valueOf((Integer.valueOf(content)/3600)));
					}
					else if(index.startsWith("review/text")){
						review.setReview(content);
					}
				}
			}
		}
		
		return review;
	}
}
